package com.baizhi.aspect;

import com.baizhi.annotation.LogAnnotation;
import com.baizhi.dao.AdminLogDao;
import com.baizhi.entity.Admin;
import com.baizhi.entity.AdminLog;
import com.baizhi.util.IPKit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

@Configuration
@Aspect
public class LogAop {

    @Resource
    private AdminLogDao adminLogDao;

    @After("@annotation(com.baizhi.annotation.LogAnnotation)")
    public void logAfter(JoinPoint joinPoint) {
        AdminLog adminLog=new AdminLog();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=requestAttributes.getRequest();
        HttpSession session=request.getSession();
        Admin admin = (Admin) session.getAttribute("login");

        adminLog.setLogIp(IPKit.getIpAddrByRequest(request));
        adminLog.setAdminId(admin.getAdminId());
        adminLog.setLogDate(new Date());

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method=signature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        String content=annotation.content();
        String type=annotation.type();

        adminLog.setLogContent(content);
        adminLog.setLogType(type);
        adminLogDao.insetAdminLog(adminLog);
    }
}
